package web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * 演示ServletContext功能四： 获取web项目下资源文件的真实路径
 */
@WebServlet("/demo7")
public class ServletDemo7 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();

        //读取项目web路径下的a.txt文件  /表示已经到达了web目录

        //a.txt放置在web目录下
        String path = servletContext.getRealPath("/a.txt");
        System.out.println(path);

        BufferedReader br = new BufferedReader(new FileReader(path));

        String s = br.readLine();
        System.out.println(s);

        //b.txt放置在WEB-INF下
        path = servletContext.getRealPath("/WEB-INF/b.txt");
        System.out.println(path);

        //c.txt放置在src下
        path = servletContext.getRealPath("/WEB-INF/classes/c.txt");
        System.out.println(path);
    }
}
